<template>
  <div>
    <el-upload
      class="avatar-uploader"
      action=""
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :http-request="upload"
    >
      <img v-if="value" :src="value" class="avatar" />
      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>
    <el-progress
      :percentage="progress"
      style="width: 230px"
      v-if="progress > 0 && progress < 100"
    ></el-progress>
  </div>
</template>

<script>
import Axios from "axios";
export default {
  name: "",
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      imageUrl: "",
      progress: 0,
    };
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = ["jpeg", "png", "gif", "webg", "svg"].includes(
        file.type.slice(6)
      );
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG) this.$message.error("请上传正确的图片格式");
      if (!isLt5M) this.$message.error("上传头像图片大小不能超过 5MB!");
      return isJPG && isLt5M;
    },
    async upload(params) {
      try {
        const formData = new FormData();
        formData.append("photo", params.file);
        const {
          data: {
            data: { photo },
          },
        } = await Axios({
          url: `http://geek.itheima.net/v1_0/user/photo`,
          method: "PATCH",
          headers: {
            Authorization: "Bearer b879621c-8dc2-47ad-a0c9-754654b9861b",
          },
          data: formData,
          // onUploadProgress 允许为上传处理进度事件
          // 浏览器专属
          onUploadProgress: (progressEvent) => {
            // 处理原生进度事件
            // console.log("progressEvent", progressEvent.loaded);
            // console.log("progressEvent", progressEvent.total);
            this.progress = parseInt(
              (progressEvent.loaded / progressEvent.total) * 100
            );
          },
        });
        // console.log(111111, photo);
        this.$emit("input", photo);
      } catch (error) {
        console.log(error);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.avatar-uploader {
  ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
